<template>
  <div class="search-container">
    <!-- 搜索栏 -->
    <!-- 在 van-search 外层增加 from 标签，且 active 不为空，即可在 ios 输入法中显示搜索按钮 -->
    <form class="search-form" action="/">
      <van-search
        v-model="searchText"
        show-action
        background="#3296fa"
        placeholder="请输入搜索关键词"
        @search="onSearch"
        @cancel="onCancel"
        @focus="isResultShow = false"
      />
    </form>

    <!-- 搜索结果 -->
    <SearchResult 
      v-if="isResultShow"
      :search-text="searchText">
    </SearchResult>
    <!-- 联想建议 -->
    <SearchSuggestion 
      v-else-if="searchText"
      :search-text="searchText"
      @search="onSearch">
    </SearchSuggestion>
    <!-- 搜索历史记录 -->
    <SearchHistory 
      v-else
      :search-histories="searchHistories"
      @clear-search-histories="searchHistories = []"
      @search="onSearch">
    </SearchHistory>
  </div>
</template>

<script>
import SearchHistory from "./components/search-history.vue"
import SearchSuggestion from "./components/search-suggestion.vue"
import SearchResult from "./components/search-result.vue"
import { setItem, getItem } from "@/utils/storage"
export default {
  name: 'SearchIndex',
  components: {
    SearchHistory,SearchSuggestion,SearchResult
  },
  data () {
    return {
      searchText: '',
      isResultShow: false, //控制搜索结果的展示
      searchHistories: getItem('TOUTIAO_SEARCH_HISTORIES') || [] //搜索的历史记录
    }
  },
  watch: {
    searchHistories (value) {
      setItem('TOUTIAO_SEARCH_HISTORIES',value)
    }
  },
  methods: {
    onSearch(val) {
      // 更新文本框内容
      this.searchText = val
      // 存储搜索历史记录
      // 需求：不要有重复记录、最新的排在最前面
      // indexOf是找元素第一次出现的位置，索引不同
      const index = this.searchHistories.indexOf(val)
      if (index !== -1) {
        this.searchHistories.splice(index,1)
      }
      this.searchHistories.unshift(val)
      // 渲染搜索结果
      this.isResultShow = true
    },
    onCancel() {
      this.$router.back()
    },
  },
}
</script>

<style scoped lang="less">
.search-container {
  padding-top: 110px;
  .van-search__action {
    color: #fff;
  }
  .search-form {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    z-index: 1;
  }
}

</style>